import { cloneDeep } from 'lodash-es'
import { http } from '@/utils/http'
import { ElMessage, ElMessageBox } from 'element-plus'

import _ from 'lodash-es'



export const useFilterStore = () => {
    const router = useRouter()
    const state = reactive({
        filterOption: {},
        filterOptions: {},
        filterShow: false,
        activefilterType: {
            name: 'all',
            display: '0'
        },
        activeNames: [],
        seasonList: [],
        showfilterName: false,
        showfilterList: false,
        filterlist: [],
        filterlistloading: false,
        listpage: {
            page: 1,
            page_size: 20,
            total: 0
        },
        showfilteredit: false,
        activeEditFilterCode: '',
        filtereditloading: false,
        activeFiltereditData: {},
        seasonList2: [],
        activeNames2: [],

        filtermatch: [],
        loadingfiltermatch: false,
        filtermatchpage: {
            page: 1,
            page_size: 20,
            total: 0
        },

        filterdata: {},
        loadingfilterdata: false,

        isopenscheme: 0
    })

    const getfilteroption = () => {
        state.filterShow = true
        http.get('/filter/get_filter_option').then(res => {
            console.log(res.data);
            state.filterOption = res.data
            getfilteroptions()
            state.filterShow = false
        }).finally(() => {
            state.filterShow = false
        })
    }

    const getfilteroptions = () => {
        let data = JSON.parse(JSON.stringify(state.filterOption))
        data.condition.forEach(item => {
            item.option_list.forEach(item2 => {
                let list = item2.option_list[0]
                if (item2.value == 'goal_trend' || item2.value == 'let_ball' || item2.value == 'big_little') {
                    item2.option_list[1] = JSON.parse(JSON.stringify(list))
                } else if (item2.value != 'corner_count' && item2.value != 'punish_count') {
                    item2.option_list[1] = JSON.parse(JSON.stringify(list))
                    item2.option_list[2] = JSON.parse(JSON.stringify(list))
                }
            });
        });

        state.filterOptions = data

        state.filtermatch = []
        state.filterdata = {}
        state.filtermatchpage = {
            page: 1,
            page_size: 20,
            total: 0
        }
    }


    const changelistsearch = () => {
        if (state.activefilterType.display == '0') {
            state.activeNames = []
        }
        if (state.activefilterType.display == '1') {
            state.activeNames = []
            let a = []
            if (state.activefilterType.name == 'all') {
                state.filterOptions.condition.forEach(item => {
                    item.option_list.forEach(item2 => {
                        a.push(item2.name)
                    })
                })
            } else {
                state.filterOptions.condition.forEach(item => {
                    if (item.name == state.activefilterType.name) {
                        item.option_list.forEach(item2 => {
                            a.push(item2.name)
                        })
                    }
                })
            }
            state.activeNames = a
        }
    }

    const getcondition = () => {
        let a = []
        state.filterOptions.condition.forEach(item => {
            if (item.name == state.activefilterType.name) {
                a = item.option_list
            }
        })
        return a
    }

    const changelazyselect = (row) => {
        state.filterOptions.season_list = []
        state.seasonList = row.season_list
    }

    const openfiltername = () => {
        if (state.filterOptions.filter_obj_code != '' && state.filterOptions.filter_obj_code != null) {
            http.post('/filter/creat_or_update_filter', state.filterOptions).then(res => {
                if (res.code == 200) {
                    ElMessage({
                        message: res.msg,
                        type: 'success',
                    })

                    state.filterOptions = res.data.filter_config_obj
                    state.showfilterList = false
                    state.filtermatch = []
                    state.filterdata = {}
                    state.filtermatchpage = {
                        page: 1,
                        page_size: 20,
                        total: 0
                    }
                    getfiltermatch(state.filterOptions.filter_obj_code)
                    getfilterdata(state.filterOptions.filter_obj_code)
                } else {
                    ElMessage.error(res.msg)
                }

            }).finally(() => {
            })
        } else {
            state.isopenscheme = 0
            state.showfilterName = true
        }

    }
    const savefilter = () => {
        console.log(state.filterOptions);
        if (state.filterOptions.filter_obj_code == '') {
            delete state.filterOptions.filter_obj_code
        }
        http.post('/filter/creat_or_update_filter', state.filterOptions).then(res => {
            if (res.code == 200) {

                state.showfilterName = false
                ElMessage({
                    message: res.msg,
                    type: 'success',
                })

                state.filterOptions = res.data.filter_config_obj
                state.showfilterList = false
                state.filtermatch = []
                state.filterdata = {}
                state.filtermatchpage = {
                    page: 1,
                    page_size: 20,
                    total: 0
                }
                console.log(state.isopenscheme);

                if (state.isopenscheme == 0) {
                    getfiltermatch(state.filterOptions.filter_obj_code)
                    getfilterdata(state.filterOptions.filter_obj_code)
                } else {
                    openscheme()
                }

            } else {
                ElMessage.error(res.msg)
            }

        }).finally(() => {
        })
    }

    const resetfilter = () => {
        getfilteroptions()
    }

    const openListdrawer = () => {
        state.filterlistloading = true
        state.listpage = {
            page: 1,
            page_size: 20,
            total: 0
        }
        getfilterlist()

    }

    const getfilterlist = () => {
        http.get(`/filter/filter_list?page=${state.listpage.page}&page_size=${state.listpage.page_size}`).then(res => {
            state.listpage.total = res.data.total
            state.filterlist = res.data.list
            state.filterlistloading = false
        }).finally(() => {
            state.filterlistloading = false
        })
    }

    const filterlistPageChange = () => {
        state.filterlistloading = true
        getfilterlist()
    }


    const deletefilter = (row) => {
        http.delete(`/filter/delete_filter?filter_obj_code=${row.filter_obj_code}`).then(res => {
            state.filterlistloading = true
            ElMessage({
                message: res.msg,
                type: 'success',
            })
            getfilterlist()
        }).finally(() => {
            ElMessage.error(res.msg)
        })

    }

    const openeditfilter = (row) => {
        state.showfilteredit = true
        state.filtereditloading = true
        state.activeEditFilterCode = row.filter_obj_code
        state.activeFiltereditData = {}
        state.activeNames2 = []
        state.seasonList2 = []
    }

    const openFilterEdit = () => {
        if (state.activeEditFilterCode != '') {
            http.get(`/filter/filter_data?filter_obj_code=${state.activeEditFilterCode}`).then(res => {
                state.activeFiltereditData = res.data.filter_config_obj
                console.log(state.activeFiltereditData);
                state.filtereditloading = false

            }).finally(() => {
            })
        }

    }
    const changelazyselect2 = (row) => {
        state.activeFiltereditData.season_list = []
        state.seasonList2 = row.season_list
    }
    const getconditionedit = () => {
        let a = []
        if (state.activeFiltereditData.condition != null) {
            state.activeFiltereditData.condition.forEach(item => {
                a = [...a, ...item.option_list]
            })
        }
        console.log(a);

        return a
    }

    const updatafilter = () => {
        console.log(state.activeFiltereditData)
        http.post('/filter/creat_or_update_filter', state.activeFiltereditData).then(res => {
            if (res.code == 200) {
                state.showfilteredit = false
                ElMessage({
                    message: res.msg,
                    type: 'success',
                })
                state.filterlistloading = true
                getfilterlist()
            } else {
                ElMessage.error(res.msg)
            }

        }).finally(() => {
        })
    }

    const clickfilterrow = (row) => {
        if (row.filter_type != 'out') {
            http.get(`/filter/filter_data?filter_obj_code=${row.filter_obj_code}`).then(res => {
                console.log(res.data.filter_config_obj);
                state.filterOptions = res.data.filter_config_obj
                state.showfilterList = false
                state.filtermatch = []
                state.filterdata = {}
                state.filtermatchpage = {
                    page: 1,
                    page_size: 20,
                    total: 0
                }
                getfiltermatch(res.data.filter_config_obj.filter_obj_code)
                getfilterdata(res.data.filter_config_obj.filter_obj_code)

            }).finally(() => {
            })
        }
    }

    const getfiltermatch = (code) => {
        state.loadingfiltermatch = true
        http.get('/filter/get_filter_match', { params: { page: state.filtermatchpage.page, page_size: state.filtermatchpage.page_size, filter_obj_code: code } }).then((res) => {
            state.filtermatch = res.data.list
            state.filtermatchpage.total = res.data.total
            state.loadingfiltermatch = false
        }).finally(() => {
            state.loadingfiltermatch = false
        })
    }


    const getfilterdata = (code) => {
        state.loadingfilterdata = true
        http.get('/filter/get_filter_data', { params: { filter_obj_code: code } }).then((res) => {
            state.loadingfilterdata = false
            state.filterdata = res.data

        }).finally(() => {
            state.loadingfilterdata = false
        })
    }

    const handlePageChange = () => {
        console.log(state.filtermatchpage);
        getfiltermatch(state.filterOptions.filter_obj_code)

    }

    const openscheme = () => {
        if (state.filterOptions.filter_obj_code != '' && state.filterOptions.filter_obj_code != null) {
            router.replace(`scheme?filter_obj_code=${state.filterOptions.filter_obj_code}`)
        } else {
            if (state.filterOptions.league_id == '') {
                ElMessage({
                    message: '请选择联赛',
                    type: 'warning',
                })
                return
            }
            if (state.filterOptions.season_list.length == 0) {
                ElMessage({
                    message: '请选择赛季时间',
                    type: 'warning',
                })
                return
            }
            state.isopenscheme = 1
            state.showfilterName = true

        }

    }

    const getmatchbyfilter = () => {
        console.log(state.filterOptions);
        if (state.filterOptions.league_id == '') {
            ElMessage({
                message: '请选择联赛',
                type: 'warning',
            })
            return
        }
        if (state.filterOptions.season_list.length == 0) {
            ElMessage({
                message: '请选择赛季时间',
                type: 'warning',
            })
            return
        }
        state.loadingfiltermatch = true
        state.loadingfilterdata = true
        http.post("/filter/match_by_filter", state.filterOptions).then((res) => {
            // console.log(res);
            state.showfilterList = false
            state.filtermatch = res.data.filter_match
            state.filterdata = res.data.filter_data
            state.loadingfiltermatch = false
            state.loadingfilterdata = false
            state.filtermatchpage = {
                page: 1,
                page_size: 20,
                total: 0
            }

        })

    }

    onMounted(async () => {
        initData()
    })

    onUnmounted(() => {
    })


    async function initData() {
        // clear()
        getfilteroption()



    }


    return {
        state,

        initData,
        changelistsearch,
        getcondition,
        changelazyselect,
        openfiltername,
        savefilter,
        resetfilter,
        openListdrawer,
        filterlistPageChange,
        deletefilter,
        openeditfilter,
        openFilterEdit,
        changelazyselect2,
        getconditionedit,
        updatafilter,
        clickfilterrow,
        handlePageChange,
        openscheme,
        getmatchbyfilter

    }
}
